package iCalendar;

import info.clearthought.layout.TableLayout;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;

import main.Main;
import Gui.NewJFrame;

import com.incors.plaf.kunststoff.KunststoffLookAndFeel;
import com.incors.plaf.kunststoff.KunststoffTheme;
import com.toedter.calendar.JCalendar;
import com.toedter.components.JLocaleChooser;

import database.Database;
import database.dateTime.DBDateTime;

/**
 *  A demonstration Applet for the JCalendar bean. The demo can also be started
 *  as Java application.
 *
 *@author     Kai Toedter
 *@version    1.1.4 07/16/02
 */
public class JCalendarDemo extends JApplet implements PropertyChangeListener {
	/**
	 *  Initializes the applet.
	 */
	public void init() {
		
		try {
			Main.initConnection("test.db3", "", "");
			db = new Database("test.db3");
		} catch (Exception e) {
			e.printStackTrace();
		}
		taskVector = new Vector<objects.Task> ();
		deadlines = new Vector<objects.Event> ();
		events = new Vector<objects.Event> ();
		// Set the Kunststoff Look And Feel:
		//initializeLookAndFeel();

		getContentPane().setLayout(new BorderLayout());
		calendarPanel = new JPanel();
		calendarPanel.setLayout(new BorderLayout());

		JPanel controlPanel = new JPanel();
		controlPanel.setLayout(new BorderLayout());
		JLocaleChooser localeChooser = new JLocaleChooser();
		localeChooser.addPropertyChangeListener(this);
		controlPanel.add(new JLabel(" Locale:   "), BorderLayout.WEST);
		controlPanel.add(localeChooser, BorderLayout.CENTER);

		dateField = new JTextField();
		dateField.setEditable(false);
		controlPanel.add(dateField, BorderLayout.NORTH);

		info = new JTextField();
		info.setText("");
		controlPanel.add(info, BorderLayout.SOUTH);
		
		JPanel myCalendarPanel = new JPanel();
		double size3 [][] = {{TableLayout.FILL}, {TableLayout.FILL, 100, TableLayout.FILL}};
		myCalendarPanel.setLayout(new TableLayout(size3));
		jcalendar1 = new JCalendar();
		jcalendar1.setBorder(new EmptyBorder(10, 10, 10, 10));
		jcalendar1.addPropertyChangeListener(this);
		jcalendar1.setToolTipText("De kalender");
		createPopupMenu();
		
		
		searchBtn = new JButton();
		searchBtn.setText("Zoek vorige deadlines");
		searchBtn.setFont(NewJFrame.startButton.getFont());
		searchBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	searchBtnActionPerformed(evt);
            }
        });
		searchBtn2 = new JButton();
		searchBtn2.setText("Zoek volgende deadlines");
		searchBtn2.setFont(NewJFrame.startButton.getFont());
		searchBtn2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	searchBtn2ActionPerformed(evt);
            }
        });
				
		editButton = new JButton();
		editButton.setText("Bekijk gebeurtenis");
		editButton.setFont(NewJFrame.startButton.getFont());
		editButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	editBtnActionPerformed(evt);
            }
        });
		
		
		
		eventList = new JList();
		JScrollPane eventScroll = new JScrollPane(eventList);
		
		JPanel buttonPanel = new JPanel();
		double size2 [][] = {{5, 200, 10, 200, 10, 200, 10, TableLayout.FILL, 5}, {30, 50}};
		buttonPanel.setLayout(new TableLayout(size2));
		buttonPanel.add(searchBtn, "1, 0      ");
		buttonPanel.add(searchBtn2, "3, 0      ");
		buttonPanel.add(editButton, "5, 0      ");
		buttonPanel.add(eventScroll, "7, 0, 7, 1");
		
		//SpringUtilities.makeCompactGrid(buttonPanel,1,
        //       buttonPanel.getComponentCount(), 6, 6, 6, 6);
		
		displayPanel = new JPanel();
		double border = 2;
		double size[][] =
        {{border, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, border},
         {TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL}};
		displayPanelLayout = new TableLayout(size);
		
		clearTable();
		
		myCalendarPanel.add(jcalendar1, "0, 0      ");
		myCalendarPanel.add(buttonPanel, "0, 1      ");
		myCalendarPanel.add(displayPanel, "0, 2      ");
		//SpringUtilities.makeCompactGrid(myCalendarPanel, myCalendarPanel.getComponentCount(),
	    //           1, 0, 0, 0, 0);
		
		
		calendarPanel.add(controlPanel, BorderLayout.NORTH);
		calendarPanel.add(myCalendarPanel, BorderLayout.CENTER);
		
		
		getContentPane().add(createMenuBar(), BorderLayout.NORTH);
		getContentPane().add(calendarPanel, BorderLayout.CENTER);

		calendar = Calendar.getInstance();
		jcalendar1.setCalendar(calendar);
	}

	
	
	/**
	 *  Installs the Kunststoff Look And Feel.
	 */
	public final void initializeLookAndFeel() {
		UIManager.put("ClassLoader", UIManager.class.getClassLoader());
		try {
			kunststoffLnF = new KunststoffLookAndFeel();
			kunststoffLnF.setCurrentTheme(new KunststoffTheme());
			UIManager.setLookAndFeel(kunststoffLnF);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			// handle exception or not, whatever you prefer
		}

		UIManager.getLookAndFeelDefaults().put("ClassLoader", getClass().getClassLoader());
	}
	

	/**
	 *  Creates the menu bar
	 *
	 *@return    Description of the Return Value
	 */
	public JMenuBar createMenuBar() {
		// Create the menu bar
		JMenuBar menuBar = new JMenuBar();

		// Menu for the look and feels (lnfs).
		UIManager.LookAndFeelInfo[] lnfs =
				UIManager.getInstalledLookAndFeels();

		ButtonGroup lnfGroup = new ButtonGroup();
		JMenu lnfMenu = new JMenu("Look&Feel");
		lnfMenu.setMnemonic('L');

		menuBar.add(lnfMenu);

		for (int i = 0; i < lnfs.length; i++) {
			if (!lnfs[i].getName().equals("CDE/Motif")) {
				JRadioButtonMenuItem rbmi =
						new JRadioButtonMenuItem(lnfs[i].getName());
				lnfMenu.add(rbmi);

				// preselect the current Look & feel
				rbmi.setSelected(
						UIManager.getLookAndFeel().getName().equals(
						lnfs[i].getName()));

				// store lool & feel info as client property
				rbmi.putClientProperty("lnf name", lnfs[i]);

				// create and add the item listener
				rbmi.addItemListener(
					// inlining
					new ItemListener() {
						public void itemStateChanged(ItemEvent ie) {
							JRadioButtonMenuItem rbmi2 =
									(JRadioButtonMenuItem) ie.getSource();
							if (rbmi2.isSelected()) {
								// get the stored look & feel info
								UIManager.LookAndFeelInfo info =
										(UIManager.LookAndFeelInfo)
										rbmi2.getClientProperty("lnf name");
								try {
									// setting the Kunststoff L&F with info.getClassName()
									// does not work with some Java Plugins
									if (info.getClassName().equals("com.incors.plaf.kunststoff.KunststoffLookAndFeel")) {
										UIManager.setLookAndFeel(kunststoffLnF);
									} else {
										UIManager.setLookAndFeel(info.getClassName());
									}
									// update the complete application's look & feel
									SwingUtilities.updateComponentTreeUI(
											JCalendarDemo.this);
								} catch (Exception e) {
									System.err.println("Unable to set UI " +
											e.getMessage());
								}
							}
						}
					}
						);
				lnfGroup.add(rbmi);
			}
		}

		// the help menu
		JMenu helpMenu = new JMenu("Help");
		helpMenu.setMnemonic('H');

		JMenuItem aboutItem = helpMenu.add(new AboutAction(this));
		aboutItem.setMnemonic('A');
		aboutItem.setAccelerator(
				KeyStroke.getKeyStroke('A', java.awt.Event.CTRL_MASK));

		menuBar.add(helpMenu);

		return menuBar;
	}
	
	private DBDateTime findClosestDeadline(DBDateTime current, boolean next) throws Exception {
		DBDateTime closest = current;
		if (events.size() != 0) {
			boolean found = false;
			
			for(int i = 0; i < events.size(); i++) {
				closest = DBDateTime.create(events.elementAt(i).getStart());
				if (next) {
					if (current.beforeDate(closest)){
						found = true;
						i = events.size();
					}
				} else {
					if (closest.beforeDate(current)){
						i = events.size();
						found = true;
					}
				}
			}
			
			if (!found) {
				
				closest = current;
			} else {
				
				for(int i = 0; i < events.size(); i++) {
					
					DBDateTime temp = DBDateTime.create((events.elementAt(i).getStart()));
					if (next) {
						
						if ((temp.beforeDate(closest)) && (current.beforeDate(temp))) {
							
							closest = temp;
						}
					} else {
						if ((closest.beforeDate(temp)) && (temp.beforeDate(current))) {
							
							closest = temp;
						}
					}
				}
			}
		}
		
		return closest;
	}
	
	private void searchBtn2ActionPerformed(java.awt.event.ActionEvent evt){
		DateFormat df = DateFormat.getDateInstance(DateFormat.LONG,
				jcalendar1.getLocale());
		String date = df.format(calendar.getTime());
		DBDateTime d = convertToDate(date);
		DBDateTime closest = new DBDateTime();
		try {
			closest = findClosestDeadline(d, true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		calendar.set(Integer.parseInt(closest.getYear()), Integer.parseInt(closest.getMonth())-1, Integer.parseInt(closest.getDay()));
		jcalendar1.setCalendar(calendar);
		dateField.setText(df.format(calendar.getTime()));
		showInfo(closest);
	}
	
	private void searchBtnActionPerformed(java.awt.event.ActionEvent evt){
		DateFormat df = DateFormat.getDateInstance(DateFormat.LONG,
				jcalendar1.getLocale());
		String date = df.format(calendar.getTime());
		DBDateTime d = convertToDate(date);
		DBDateTime closest = new DBDateTime();
		try {
			closest = findClosestDeadline(d, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
		calendar.set(Integer.parseInt(closest.getYear()), Integer.parseInt(closest.getMonth())-1, Integer.parseInt(closest.getDay()));
		jcalendar1.setCalendar(calendar);
		dateField.setText(df.format(calendar.getTime()));
		showInfo(closest);
	}
	

	
	private void editBtnActionPerformed(java.awt.event.ActionEvent evt){
		//NewJFrame.gebeurtenisVenster = new JFrame();
		NewJFrame.gebeurtenisVenster.pack();
		NewJFrame.gebeurtenisVenster.setLocationRelativeTo(null);
		NewJFrame.gebeurtenisVenster.setVisible(true);
		String summary = (String) eventList.getSelectedValue();
		DateFormat df = DateFormat.getDateInstance(DateFormat.LONG,
				jcalendar1.getLocale());
		String date = df.format(calendar.getTime());
		DBDateTime current = convertToDate(date);
		int index = eventList.getSelectedIndex();
		try {
			objects.Event event =getCurrentEvents(current).elementAt(index);
			NewJFrame.jTextPane5.setText(event.getSummary());
			NewJFrame.jTextPane6.setText(event.getMoreInformation());
			DBDateTime start = DBDateTime.create(event.getStart());
			NewJFrame.jComboBox12.setSelectedItem(start.getYear());
			NewJFrame.jComboBox13.setSelectedItem(start.getMonth());
			NewJFrame.jComboBox14.setSelectedItem(start.getDay());
			NewJFrame.jComboBox15.setSelectedItem(start.getHours());
			NewJFrame.jComboBox16.setSelectedItem(start.getMinutes());
			if (event.getEnd() != null) {
				DBDateTime end = DBDateTime.create(event.getEnd());
				NewJFrame.jComboBox17.setSelectedItem(end.getYear());
				NewJFrame.jComboBox18.setSelectedItem(end.getMonth());
				NewJFrame.jComboBox19.setSelectedItem(end.getDay());
				NewJFrame.jComboBox20.setSelectedItem(end.getHours());
				NewJFrame.jComboBox21.setSelectedItem(end.getMinutes());
			}
			if (event.getWarningDate() != null) {
				DBDateTime warn = DBDateTime.create(event.getWarningDate());
				NewJFrame.jComboBox22.setSelectedItem(warn.getYear());
				NewJFrame.jComboBox23.setSelectedItem(warn.getMonth());
				NewJFrame.jComboBox24.setSelectedItem(warn.getDay());
				NewJFrame.jComboBox25.setSelectedItem(warn.getHours());
				NewJFrame.jComboBox26.setSelectedItem(warn.getMinutes());
			}
			NewJFrame.gebeurtenisVenster.pack();
			NewJFrame.gebeurtenisVenster.setLocationRelativeTo(null);
			NewJFrame.gebeurtenisVenster.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private void popUpActionPerformed(java.awt.event.ActionEvent evt){
		System.out.println("!");
	}
	
	/**
	 *  The applet is a PropertyChangeListener for "locale" and "calendar".
	 *
	 *@param  evt  Description of the Parameter
	 */
	public void propertyChange(PropertyChangeEvent evt) {
		
		if (calendarPanel != null) {
			if (evt.getPropertyName().equals("locale")) {
				jcalendar1.setLocale((Locale) evt.getNewValue());
				DateFormat df = DateFormat.getDateInstance(DateFormat.LONG,
						jcalendar1.getLocale());
				String date = df.format(calendar.getTime());
				DBDateTime d = convertToDate(date);
				calendar.set(Integer.parseInt(d.getYear()), Integer.parseInt(d.getMonth())-1, Integer.parseInt(d.getDay()));
				jcalendar1.setCalendar(calendar);
				dateField.setText(df.format(calendar.getTime()));
				
				showInfo(d);
			} else if (evt.getPropertyName().equals("calendar")) {
				calendar = (Calendar) evt.getNewValue();
				DateFormat df = DateFormat.getDateInstance(DateFormat.LONG,
						jcalendar1.getLocale());
				String date = df.format(calendar.getTime());
				DBDateTime d = convertToDate(date);
				calendar.set(Integer.parseInt(d.getYear()), Integer.parseInt(d.getMonth())-1, Integer.parseInt(d.getDay()));
				jcalendar1.setCalendar(calendar);
				dateField.setText(df.format(calendar.getTime()));
				showInfo(d);
			}			
		}
	}
	
	public void clearTable(){
		double border = 2;
		double size[][] =
        {{border, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, border},
         {TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL, TableLayout.FILL}};
		displayPanelLayout = new TableLayout(size);
		displayPanel.setLayout(displayPanelLayout);
		JTextField title = new JTextField("Type:");
		JTextField name = new JTextField("Taak naam:");
		JTextField desc = new JTextField("Beschrijving:");
		JTextField grades = new JTextField("Punten:");
		JTextField extra = new JTextField("Extra info:");
		JTextField done = new JTextField("Afgewerkt:");
		
		Color c = new Color(214,215,250);
		
		String letterType = "Arial";
		title.setBackground(c);
		title.setFont(new Font(letterType, Font.BOLD, 14));
		title.setHorizontalAlignment(JTextField.CENTER);
		title.setEditable(false);
		name.setBackground(c);
		name.setFont(new Font(letterType, Font.BOLD, 14));
		name.setHorizontalAlignment(JTextField.CENTER);
		name.setEditable(false);
		desc.setBackground(c);
		desc.setFont(new Font(letterType, Font.BOLD, 14));
		desc.setHorizontalAlignment(JTextField.CENTER);
		desc.setEditable(false);
		grades.setBackground(c);
		grades.setFont(new Font(letterType, Font.BOLD, 14));
		grades.setHorizontalAlignment(JTextField.CENTER);
		grades.setEditable(false);
		extra.setBackground(c);
		extra.setFont(new Font(letterType, Font.BOLD, 14));
		extra.setHorizontalAlignment(JTextField.CENTER);
		extra.setEditable(false);
		done.setBackground(c);
		done.setFont(new Font(letterType, Font.BOLD, 16));
		done.setHorizontalAlignment(JTextField.CENTER);
		done.setEditable(false);
		
		displayPanel.add(title, "1, 0");
		displayPanel.add(name, "1, 1");
		displayPanel.add(desc, "1, 2");
		displayPanel.add(grades, "1, 3");
		displayPanel.add(extra, "1, 4");
		displayPanel.add(done, "1, 5");
	}
	
	private boolean inTaskList(objects.Task task) {
		String name = task.getName();
		boolean check = false;
		for (int i = 0; i < taskVector.size(); i++) {
			if (compareStrings(taskVector.elementAt(i).getName(), name)) {
				check = true;
			}
		}
		return check;
	}
	
	private void makeTaskVector(Vector<objects.Task> v) {
		try {
			taskVector.clear();
			for (int i = 0; i < v.size(); i++) {
				objects.Exam exam = db.exam.getExam(v.elementAt(i).getName());
				objects.Project project = db.proj.getProject(v.elementAt(i).getName());
				objects.Task task = db.task.getTask(v.elementAt(i).getName());
				if (exam != null) {
					taskVector.add(exam);
				} else if (project != null) {
					taskVector.add(project);
				} else if (task != null) {
					taskVector.add(task);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	private Vector<objects.Event> getCurrentEvents(DBDateTime date) {
		Vector<objects.Event> current = new Vector<objects.Event>();
		taskVector.clear();
		try {
			for (int i = 0; i < events.size(); i++) {
				if (DBDateTime.compareDates(events.elementAt(i).getStart(), date.toString())) {
					Vector<objects.Task> v = db.rTE.getTasks(events.elementAt(i).getStart(), events.elementAt(i).getSummary());
					if (v.size() == 0) {
						current.add(events.elementAt(i));
					} else {
						for (int j = 0; j < v.size(); j++) {
							objects.Exam exam = db.exam.getExam(v.elementAt(j).getName());
							objects.Project project = db.proj.getProject(v.elementAt(j).getName());
							objects.Task task = db.task.getTask(v.elementAt(j).getName());
							if (exam != null) {
								taskVector.add(exam);
							} else if (project != null) {
								taskVector.add(project);
							} else if (task != null) {
								taskVector.add(task);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return current;
	}
	
	public void showInfo(DBDateTime date){
		String title = "";
		String name = "";
		String desc = "";
		String grades = "";
		String extra = "";
		String done = "";
		String infoText = "";
		editButton.setEnabled(false);
		eventList.setListData(new Vector<String>());
		eventList.setEnabled(false);
		clearTable();
		info.setBackground(new Color(255, 255, 255));
		info.setText("");
		int column = 2;
		try {
			events = db.event.getAllEvents(true);
			deadlines = db.event.getAllDeadlines();
			Vector<objects.Event> temp = getCurrentEvents(date);
			if (temp.size() != 0) {
				info.setBackground(new Color(255, 0, 0));
				infoText = "Er zijn 1 of meer gebeurtenissen op deze dag. Klik op 'Bekijk Gebeurtenis' voor meer informatie";
				eventList.setEnabled(true);
				editButton.setEnabled(true);
				Vector<String> v = new Vector<String> ();
				for (int i = 0; i < temp.size(); i++) {
					v.add(i, temp.elementAt(i).getSummary());
				}
				eventList.setListData(v);
				eventList.setSelectedIndex(0);
			}
			for (int j = 0; j < taskVector.size(); j++) {
				if (taskVector.get(j) instanceof objects.Exam) {
					title = "Examen";
				} else if (taskVector.get(j) instanceof objects.Project) {
					title = "Project";
				} else {
					title = "Taak";
				}
				
				name = taskVector.get(j).getName();
				desc = taskVector.get(j).getDescription();
				grades = taskVector.get(j).getGrades();
				extra = taskVector.get(j).getMoreInformation();
				if (taskVector.get(j).getDone() == "T") {
					done = "ja";
				} else {
					done = "nee";
				}
				JTextField titleField = new JTextField (title);
				dateField2 = new JTextField(name);
				dateField3 = new JTextField(desc);
				dateField4 = new JTextField(grades);
				dateField5 = new JTextField(extra);
				dateField6 = new JTextField(done);
				
				dateField2.setLayout(new BorderLayout());
				dateField2.setToolTipText("Taak naam");
				dateField2.setFont(NewJFrame.startButton.getFont());
				dateField2.setEditable(false);
				dateField2.setHorizontalAlignment(JTextField.CENTER);
				
				dateField3.setLayout(new BorderLayout());
				dateField3.setToolTipText("Beschrijving");
				dateField3.setFont(NewJFrame.startButton.getFont());
				dateField3.setEditable(false);
				dateField3.setHorizontalAlignment(JTextField.CENTER);
				
				dateField4.setLayout(new BorderLayout());
				dateField4.setToolTipText("Punten");
				dateField4.setFont(NewJFrame.startButton.getFont());
				dateField4.setEditable(false);
				dateField4.setHorizontalAlignment(JTextField.CENTER);
				
				dateField5.setLayout(new BorderLayout());
				dateField5.setToolTipText("Extra info...");
				dateField5.setFont(NewJFrame.startButton.getFont());
				dateField5.setEditable(false);
				dateField5.setHorizontalAlignment(JTextField.CENTER);
				
				dateField6.setLayout(new BorderLayout());
				dateField6.setToolTipText("Afgewerkt?");
				dateField6.setFont(NewJFrame.startButton.getFont());
				dateField6.setHorizontalAlignment(JTextField.CENTER);
				dateField6.setEditable(false);
				
				
				titleField.setBackground(new Color(214,215,250));
				titleField.setFont(NewJFrame.startButton.getFont());
				titleField.setHorizontalAlignment(JTextField.CENTER);
				titleField.setEditable(false);
				
				displayPanel.add(titleField, column + ", 0");
				displayPanel.add(dateField2, column + ", 1");
				displayPanel.add(dateField3, column + ", 2");
				displayPanel.add(dateField4, column + ", 3");
				displayPanel.add(dateField5, column + ", 4");
				displayPanel.add(dateField6, column + ", 5");
				column++;
			}
			displayPanel.validate();
			DBDateTime d1 = findClosestDeadline(date, false);
			objects.Event event = null;
			for (int i = 0; i < events.size(); i++) {
				if (DBDateTime.compareDates(events.elementAt(i).getStart(), d1.toString())) {
					event = events.get(i);
					break;
				}
			}
			if ((event != null) && (event.getEnd() != null)) {
				DBDateTime d2 = DBDateTime.create(event.getEnd());
				if (!d2.beforeDate(date)) {
					infoText = infoText + " Er is nog een gebeurtenis bezig die " + d1.getDay() + "/" + d1.getMonth()
					+ "/" + d1.getYear() + " gestart is.";
				}
			}
			info.setText(infoText);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private int convertMonthToInt(String month) {
		if (compareStrings(month,"januari")) {
			return 1;
		} else if (compareStrings(month,"februari")) {
			return 2;
		} else if (compareStrings(month,"maart")) {
			return 3;
		} else if (compareStrings(month,"april")) {
			return 4;
		} else if (compareStrings(month,"mei")) {
			return 5;
		} else if (compareStrings(month,"juni")) {
			return 6;
		} else if (compareStrings(month,"juli")) {
			return 7;
		} else if (compareStrings(month,"augustus")) {
			return 8;
		} else if (compareStrings(month,"september")) {
			return 9;
		} else if (compareStrings(month,"oktober")) {
			return 10;
		} else if (compareStrings(month,"november")) {
			return 11;
		} else if (compareStrings(month,"december")) {
			return 12;
		}
		return 0;
	}
	
	private static boolean compareStrings(String s1, String s2){
		// vergelijkt 2 Strings
		if (s1.length() != s2.length()){
			return false;
		} else {
			for (int i = 0; i<s1.length(); i++){
				if (s1.charAt(i) != s2.charAt(i)) {
					return false;
				}
			}
		}
		return true;
	}
	
	public DBDateTime convertToDate(String date) {
		int day = 0;
		int month = 0;
		int year = 0;
		String monthString = "";
		int counter = 0;
		while (date.charAt(counter) != ' ') {
			day = day * 10 + date.charAt(counter) - 48;
			counter++;
		}
		counter++;
		while (date.charAt(counter) != ' ') {
			monthString = monthString + date.charAt(counter); 
			counter++;
		}
		counter++;
		month = convertMonthToInt(monthString);
		while (counter < date.length()) {
			year = year * 10 + date.charAt(counter) - 48;
			counter++;
		}
		DBDateTime d = new DBDateTime();
		try {
			d = DBDateTime.create(day, month, year, 23 ,59, 59);
		} catch(Exception e) {
			e.printStackTrace();
		}
		
		
		
		return d;
	}

	/**
	 *  Action to show the About dialog
	 *
	 *@author    toedter_k
	 */
	class AboutAction extends AbstractAction {
		/**
		 *  Constructor for the AboutAction object
		 *
		 *@param  demo  Description of the Parameter
		 */
		AboutAction(JCalendarDemo demo) {
			super("About...");
			this.demo = demo;
		}


		/**
		 *  Description of the Method
		 *
		 *@param  event  Description of the Parameter
		 */
		public void actionPerformed(ActionEvent event) {
			
			JOptionPane.showMessageDialog(demo, "JCalendar Demo\nVersion 1.1\n\nKai Toedter\nkai@toedter.com\nwww.toedter.com",
					"About...", JOptionPane.INFORMATION_MESSAGE);
		}


		private JCalendarDemo demo;
	}


	/**
	 *  Creates a JFrame with a JCalendarDemo inside and can be used for testing.
	 *
	 *@param  s  The command line arguments
	 */
	public static void main(String[] s) {
		
		WindowListener l =
			new WindowAdapter() {
				public void windowClosing(WindowEvent e) {
					System.exit(0);
				}
			};
		
		JFrame frame = new JFrame("JCalendar Demo");
		frame.addWindowListener(l);
		JCalendarDemo demo = new JCalendarDemo();
		demo.init();
		frame.getContentPane().add(demo);
		frame.pack();
		frame.setVisible(true);
	}
	
	public void createPopupMenu() {
        JMenuItem menuItem;
        String space = "               ";
        //Create the popup menu.
        JPopupMenu popup = new JPopupMenu();
        menuItem = new JMenuItem("Voeg gebeurtenis toe" + space);
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	popUpActionPerformed(evt);
            }
        });
        
        popup.add(menuItem);
        menuItem = new JMenuItem("Bewerk gebeurtenis" + space);
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	popUpActionPerformed(evt);
            }
        });
        popup.add(menuItem);
        
        menuItem = new JMenuItem("Verwijder gebeurtenis" + space);
        menuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	popUpActionPerformed(evt);
            }
        });
        popup.add(menuItem);
        
        //Add listener to the text area so the popup menu can come up.
        MouseListener popupListener = new PopupListener(popup);
        
        jcalendar1.addMouseListener(popupListener);
    }

	public void setCalendarPanel(JPanel newCalendarPanel){
		calendarPanel = newCalendarPanel;
	}
	
	public JPanel getCalendarPanel(){
		return this.calendarPanel;
	}
	
    class PopupListener extends MouseAdapter {
        JPopupMenu popup;

        PopupListener(JPopupMenu popupMenu) {
            popup = popupMenu;
        }

        public void mousePressed(MouseEvent e) {
            maybeShowPopup(e);
        }

        public void mouseReleased(MouseEvent e) {
            maybeShowPopup(e);
        }

        private void maybeShowPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
                popup.show(e.getComponent(),
                           e.getX(), e.getY());
            }
        }
    }
	
	private JPanel calendarPanel;
	private JPanel displayPanel;
	private TableLayout displayPanelLayout;
	private Database db; 
	private JCalendar jcalendar1;
	private JButton searchBtn;
	private JButton searchBtn2;
	private JButton editButton;
	private JTextField dateField;
	private JTextField dateField2;
	private JTextField dateField3;
	private JTextField dateField4;
	private JTextField dateField5;
	private JTextField dateField6;
	private JTextField info;
	private JList eventList;
	
	private JLocaleChooser localeChooser;
	private Calendar calendar;
	private KunststoffLookAndFeel kunststoffLnF;
	private Vector<objects.Task> taskVector;
	private Vector<objects.Event> deadlines;
	private Vector<objects.Event> events;
}








